package com.group.service;

import com.group.dao.GeneralBeanDao;
import com.group.dao.InviteRebateDao;
import com.group.model.*;
import com.group.util.NoteException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;

@Service
public class InviteRebateService {

    @Autowired
    InviteRebateDao inviteRebateDao;
    @Autowired
    GeneralBeanDao beanDao;
    @Autowired
    TickerService tickerService;

    @Transactional
    public String SaveRebateDetail(Long userId, Long refUserId, double fee, double invFee){
        Long now = System.currentTimeMillis();
        ReferenceDetail rd = new ReferenceDetail();
        rd.setUserId(userId);
        rd.setRefUserId(refUserId);
        rd.setCreateDate(now);
        ReferenceWallet rw = inviteRebateDao.selectByUserId(userId);
        if(rw != null){
            rd.setChange(rw.getWallet() + fee);
            rd.setVersion(rw.getVersion());
            rd.setInvestment(invFee);
            rd.setRebate(fee);
            rd.setVersion(rw.getVersion() + 1);
            int i = inviteRebateDao.updateByVersion(rw.getWallet()+fee, rw.getUserId(), rw.getVersion());
            if(i != 1){
                throw new NoteException("系统繁忙，请稍后再试!");
            }
        }else{
            ReferenceWallet r = new ReferenceWallet();
            r.setUserId(userId);
            r.setWallet(fee);
            r.setVersion(1);
            r.setCreateDate(now);
            beanDao.save(r);
            rd.setVersion(r.getVersion());
            rd.setChange(fee);
            rd.setInvestment(invFee);
            rd.setRebate(fee);
        }
        beanDao.save(rd);
        return "OK";
    }

    @Transactional
    public Boolean Transfer(Long userId){
        Date now = new Date();
        Boolean flag = false;
        ReferenceWallet rw = inviteRebateDao.selectByUserId(userId);
        if(rw == null){
            throw new NoteException("钱包异常!");
        }
        if(rw.getWallet() == 0){
            throw new NoteException("您的余额为0");
        }
        int i = inviteRebateDao.updateByVersion(0.0, userId, rw.getVersion());
        if(i != 1){
            throw new NoteException("系统繁忙，请稍后再试！");
        }
        flag = true;
        tickerService.addTicker(userId, "wecc", rw.getWallet(), "返佣提币");
        return flag;
    }
}
